package com.thd.springboottest.security.securitycustom;

import com.thd.springboottest.security.utils.R;
import com.thd.springboottest.security.utils.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用来解决匿名用户访问无权限资源时的异常
 *
 * @author: wanglei62
 * @DATE: 2022/6/23 14:12
 **/
@Component("myAuthenticationEntryPoint")
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("application/json");
//        PrintWriter out = response.getWriter();
//
//        out.write("登录失败! 我在MyAuthenticationEntryPoint输出");
//        out.flush();
//        out.close();
        ServletUtils.getInstance().failure(response, R.failure("Un Login  , Please Login First"));
    }
}